/*
 * @Author: your name
 * @Date: 2021-11-12 21:33:25
 * @LastEditTime: 2021-11-15 17:15:31
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\serve\app\service\article.js
 */
/*
 * @Author: your name
 * @Date: 2021-11-10 08:34:30
 * @LastEditTime: 2021-11-11 09:09:44
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\egg-example\app\service\login.js
 */

const Service = require("egg").Service;
class EmailService extends Service {
    //获取文章数据 +分页 +搜索
    async getEmail() {
        const { ctx, app } = this;
        const { pageSize, pageIndex, addresser, addressee, themeVal } =
        ctx.request.body;
        let res = await app.mysql.select("email");
        let total = res.length;
        //发件人
        if (addresser) {
            res = res.filter((item) => {
                if (
                    item.addresser.indexOf(addresser) !== -1 ||
                    item.addresser.includes(addresser)
                ) {
                    return item;
                }
            });
            total = res.length;
        }
        //收件人
        if (addressee) {
            res = res.filter((item) => {
                if (
                    item.addressee.indexOf(addressee) !== -1 ||
                    item.addressee.includes(addressee)
                ) {
                    return item;
                }
            });
            total = res.length;
        }
        if (themeVal) {
            res = res.filter((item) => {
                if (
                    item.theme.indexOf(themeVal) !== -1 ||
                    item.theme.includes(themeVal)
                ) {
                    return item;
                }
            });
            total = res.length;
        }
        //分页
        res = res.slice((pageIndex - 1) * pageSize, pageSize * pageIndex);
        //时间倒序
        res.sort((a, b) => {
            return new Date(b.public_time) - new Date(a.public_time);
        });
        return { res, total };
    }

    //删除
    async delEmail() {
        const { ctx, app } = this;
        const { id } = ctx.request.body;
        const res = await app.mysql.delete("email", {
            id,
        });
        return res;
    }

    //批量删除
    async batchDelEmail() {
        const { ctx, app } = this;
        const { batchList } = ctx.request.body;
        batchList.forEach((item) => {
            app.mysql.delete("email", {
                id: item.id,
            });
        });
        return "操作成功";
    }
}
module.exports = EmailService;